<?php
class SubjectsController extends AppController {

    var $name = 'Subjects';
    var $components = array('RequestHandler', 'Access');
    var $paginate = array(
        'limit' => '20',
        'order' => array('Subject.subject' => 'desc')
    );
    var $uses = array('Tag', 'Adjective', 'Subject', 'Credit', 'UserCredit', 'FlaggedSubject', 'Page', 'Pageredirect', 'Subjectredirect');

    function beforeFilter() {


        $this->Auth->loginRedirect = array('controller' => 'Dashboard', 'action' => 'index');
        $this->Auth->allow('login_element', 'subject', 'rate', 'synonyms', 'get_suggestion', 'get_redirects', 'adjectives', 'generatepopupimage');
    }

    function admin_index() {

        if (!$this->Access->check('Subject', 'read')) {
            $this->Session->setFlash(__("You don't have permissions to View this content"));
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (isset($this->params['named']['status'])) {
            $this->paginate = array(
                'limit' => '20',
                'order' => array('Subject.created' => 'desc'),
                'conditions' => array('Subject.status' => $this->params['named']['status'])
            );
        }
        $data = $this->paginate('Subject');
        $adjectives = '';
        $taglist = '';
        $i = 0;

        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */

        foreach ($data as $value) {
           $adj_ids = Set::classicExtract($value['SubjectAdjectives'], '{n}.adjective_id');
           
            //$adj_ids = implode(',', $result);debug($adj_ids);
            $tag_ids = explode(',', $value['Subject']['tag_ids']);

            /*             * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
            foreach ($adj_ids as $id) {
                $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $id)));
                $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
            }


            /*             * ************** 
             * This loop will get all the formated tags for a particular record.
             *  Functions used : 
             *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
             *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
             * 
             * *************** */
            foreach ($tag_ids as $tid) {
                $tag_arr = $this->get_parent_list($tid);
                $taglist = $this->formated_tags($tag_arr, '>');
            }
            $data[$i]['Subject']['adjective_ids'] = substr($adjectives, 1);
            $data[$i]['Subject']['tag_ids'] = $taglist;
            $i++;
            $adjectives = '';
            //$tags='';
        }

        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('Subjects', $data);
    }

    function admin_approve($id=null) {
        if (!$this->Access->check('User', 'read')) {
            $this->Session->setFlash('You dont have permissions to View this content');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!empty($id) || isset($this->data)) {

            if (empty($this->data)) {
                $data = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id, 'Subject.status =' => '0'), 'recursive' => '2'));
                if (!$data) {
                    $this->Session->setFlash('Subject Already approved.Cant approve again ');
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
                }
                $this->admin_edit($id);
                $credits = $this->Credit->find('all');
                $urating = $this->Subject->query("SELECT subject_rates.rating, user_id FROM `subject_rates` where subject_id='$id'");
                $this->set('credits', $credits);
            } else {
                $redirect = true;                             //We will set $redirect to true so that admin_edit does not redirect as we want the control back for further process 
                $this->admin_edit($this->data, $redirect);
                $this->saveCredit($this->data);
                $update = mysql_query("Update `subject` set status='1',`approved_by`='" . $_SESSION['Auth']['User']['id'] . "',`approved_on`='NOW()' where subject.id='" . $this->data['Subject']['id'] . "'");
                $this->Session->setFlash('Subject Approved.');

                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));


                //debug($this->data);
            }
        } else {
            $this->Session->setFlash('Subject not available ');
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
    }

    function admin_add() {
        if (!$this->Access->check('Subject', 'create')) {
            $this->Session->setFlash("You can't add new subjects");
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (isset($this->data)) {

            $tags = array();

            if (isset($_POST['tag_ids'])) {
                $tags = $_POST['tag_ids'];
            }
            $uniquetags = array_unique($tags);

            $tag_ids = implode(',', $uniquetags);
            $tag_ids = ltrim($tag_ids, ',');
            $this->data['Subject']['tag_ids'] = $tag_ids;

            if ($this->data['Subject']['image']['error'] == '0') {
                $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                if ($this->check_image_extension($ext['extension'])) {
                    $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                    if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                        move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                    }
                    $this->data['Subject']['image'] = $image_name;
                } else {
                    $this->data['Subject']['image'] = '';
                }
            } else {
                $this->data['Subject']['image'] = '';
            }
            $this->data['Subject']['user_id'] = $_SESSION['Auth']['User']['id'];
            $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);

            //$this->data=$this->set_adjective_array($this->data);
            if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {

                $this->admin_save_adjectives($this->data['Subject']['adjective_ids'], $this->Subject->id);
                $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];
                $this->Subject->SubjectRate->save($this->data, array('validate' => 'only'));
                $this->Session->setFlash('Subject Saved');
                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));
            }
        }
    }

    function admin_save_adjectives($adjective_ids, $subject_id) {

        if ($adjective_ids) {
            $adjective_ids = explode(',', $adjective_ids);
            foreach ($adjective_ids as $adjective):
                $save_adjective = mysql_query("INSERT into `subject_adjectives` (`adjective_id`,`subject_id`,`user_id`,`created`) 
                    VALUES('" . $adjective . "','" . $subject_id . "','" . $_SESSION['Auth']['User']['id'] . "',NOW())");
            endforeach;
            return true;
        }
        return false;
    }

   

    function admin_edit($id=null, $redirect=null) {                      //We have introduced second argument to override the default redirect on successfull save. When set to true this method will not redirect.
        if (!$this->Access->check('Subject', 'update')) {
            $this->Session->setFlash('Permission denied. Please contact your Administrator for more permissions');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if ($id) {
            if (empty($this->data)) {

                $this->data = $this->Subject->read(null, $id);
                $this->data['adjective_ids']='';
                if(!$this->data){
                     $this->Session->setFlash('Subject not available ');
                     $this->redirect(array('controller' => 'Subjects', 'action' => 'index','status'=>'1'));
                }else{
                $subjecttitle = json_encode(array('0' => array('id' => $this->data['Subject']['subject'], 'name' => $this->data['Subject']['subject'])));
                $this->set('subjecttitle', $subjecttitle);
                if (($this->Access->check('User', 'update')) || ($this->data['Subject']['user_id'] == $_SESSION['Auth']['User']['id'] && $this->data['Subject']['status'] == '0')) {
                    $tags = array();
                    if (!empty($this->data['SubjectAdjectives'])) {
                        $adjective_ids=Set::classicExtract($this->data['SubjectAdjectives'],'{n}.adjective_id');
                        $subject_adjective_ids=Set::classicExtract($this->data['SubjectAdjectives'],'{n}.id');
                        $this->data['adjective_ids']=implode(',',$subject_adjective_ids);
                        $adjective_ids=array_combine($subject_adjective_ids, $adjective_ids);
                            $adjectivelist = $this->adjectivelist($adjective_ids);
                        $this->set('adjectivelist', $adjectivelist);
                    }
                    $tag_ids = explode(',', $this->data['Subject']['tag_ids']);
                    foreach ($tag_ids as $tid) {
                        $tag_arr = $this->get_parent_list($tid);
                        $taglist = $this->formated_tags($tag_arr, '>');
                        $tag_arr = array('tag_id' => $tid, 'tag' => $taglist);
                        array_push($tags, $tag_arr);
                    }

                    $this->data['Subject']['taglist'] = $tags;

                    $this->set('id', $id);
                    /*                     * *****Prepopulate Adjective list******** */
                } else {
                    $this->Session->setFlash('You can only Edit your own submitted Subjects');
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));
                }
            }} else {
             //debug($this->data);
               $this->data['Subject']['old_adjectives']=explode(',',$this->data['Subject']['old_adjectives']);
              
              $this->data['Subject']['adjective_ids']=explode(',',$this->data['Subject']['adjective_ids']);
              if(!empty($this->data['Subject']['old_adjectives']['0'])){
                  
              foreach($this->data['Subject']['old_adjectives'] as $old_adjectives):
                  //echo $old_adjectives;
                  if(!in_array($old_adjectives,$this->data['Subject']['adjective_ids'])){
                          $delete_adjective=mysql_query("DELETE FROM `subject_adjectives` WHERE `id`='".$old_adjectives."'");
                  
                         // echo "<br>";
                  }
                  //echo "<br>";
              endforeach;
              //die('dsda');
              }else{
                  //die('else');
                  
                  $adjective_id=explode(',',$this->data['Subject']['adjective_ids']);
                  
                  if(count($adjective_id)>0){
                  foreach($adjective_id as $id){
                      $add_new_adjective=mysql_query("INSERT INTO `subject_adjectives` (`adjective_id`,`user_id`,`subject_id`,`created`) VALUES ('".  $id."','".$this->Auth->User('id')."','".$this->data['Subject']['id']."',NOW())");
                      
                  }
                  }
                  
                  
                  
              }
                $tag_ids = null;
                $this->Subject->id = $this->data['Subject']['id'];
                if (isset($_POST['tag_ids'])) {
                    $tags = $_POST['tag_ids'];
                    //if(!empty($_POST['data']['Subject']['tag_ids'])){array_push($tags, $_POST['data']['Subject']['tag_ids']);}
                    $uniquetags = array_unique($tags);
                    //debug($uniquetags);die();
                    $tag_ids = implode(',', $uniquetags);
                    $tag_ids = ltrim($tag_ids, ',');
                }
                $this->data['Subject']['tag_ids'] = $tag_ids;

//debug($tag_ids);debug($uniquetags);die();  
                if (isset($this->data['Subject']['image'])) {
                    if ($this->data['Subject']['image']['error'] != '0') {
                        $this->data['Subject']['image'] = '';
                    } else {
                        $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                        if ($this->check_image_extension($ext['extension'])) {
                            $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                            $filename = WWW_ROOT . 'img/uploads/Subjects/' . $image_name;
                            if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                                move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                            }

                            /*   if ($this->Subject->validates(array('fieldlist' => array('image')))) {
                              if (!is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {

                              mkdir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject']);

                              chmod(WWW_ROOT . 'img/uploads/Subjects/'. $this->data['Subject']['subject'],'0777');
                              $path = WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'];
                              } elseif (is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {
                              if (!empty($this->data['Subject']['image'])) {

                              move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'] . '/' . $this->data['Subject']['image']['name']);
                              } else {
                              $this->Session->setFlash('Somthing went wrong uploading image');
                              }
                              }
                              } */
                            $this->data['Subject']['image'] = $image_name;
                        } else {
                            $this->data['Subject']['image'] = null;
                        }
                    }
                }
                $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);  // Convert specifier to lowercase
                if (isset($_POST['rating_id'])) {
                    if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {
                        $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                        $this->data['SubjectRate']['id'] = $_POST['rating_id'];
                        $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                        $this->data['SubjectRate']['rating'] = $_POST['rating'];
                        $this->Subject->SubjectRate->save($this->data);
                        $this->Session->setFlash('Subject Saved');

                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->data['Subject']['status']));
                    }
                } else {


                    $this->Subject->set($this->data);
                    //debug($this->data);die();
                    $this->Subject->save($this->data, array('validate' => false));     //dont validate on edit
//debug($this->data);die();

                    if (!$redirect) {
                        $this->Session->setFlash('Subject Updated ');
                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->data['Subject']['status']));
                    }
                }
            }
             } else {
            $this->Session->setFlash('Subject not available ');
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
    }
    
    /***************** This function is used in admin_edit to set Adjective ids for edit page*********************/
    
function adjectivelist($adjective_ids) {
        $i = 0;
        foreach ($adjective_ids as $key=>$id) {
            $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id' => $id),'fields'=>array('Adjective.id','Adjective.title')));
            $adjectives[$i]['id'] = $key;
            $adjectives[$i]['name'] = $adj['Adjective']['title'];
            $i++;
        }

        //$adjectivelist = substr($adjectives, 1);
        return $adjectives;
    }
    function admin_view($id=null) {

        $adjectives = '';
        $taglist = '';
        $tags = array();
        $i = 0;
        $data = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id)), array('resursive' => '2'));


        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */
        $adj_ids=array_unique(Set::classicExtract($data['SubjectAdjectives'],'{n}.adjective_id'));
        
        $tag_ids = explode(',', @$data['Subject']['tag_ids']);

        /*         * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
       
        foreach ($adj_ids as $aid) {
            $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $aid)));
            $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
        }


        /*         * ************** 
         * This loop will get all the formated tags for a particular record.
         *  Functions used : 
         *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
         *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
         * 
         * *************** */
        foreach ($tag_ids as $tid) {
            $tag_arr = $this->get_parent_list($tid);
            $taglist = $this->formated_tags($tag_arr, '>');
            $tag_arr = array('tag_id' => $tid, 'tag' => $taglist);
            array_push($tags, $tag_arr);
        }
        $data['Subject']['adjective_ids'] = substr($adjectives, 1);
        $data['Subject']['tag_ids'] = $tags;
        $i++;
        $adjectives = '';
        $tags = array();


        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('subjects', $data);
        $related_subjects = $this->get_related_subjects($data['Subject']['subject']);
        $this->set('related_subjects', $related_subjects);
        $lastRated = $this->Subject->SubjectRate->find('first', array(
            'conditions' => array(
                'SubjectRate.subject_id' => $id,
                'SubjectRate.user_id' => $_SESSION['Auth']['User']['id']
            ),
            'order' => 'SubjectRate.created desc',
            'limit' => '1'
                )
        );
        $this->set('lastrated', $lastRated);
    }

    function admin_delete($id=null) {
        if (!$this->Access->check('Subject', 'delete')) {
            $this->Session->setFlash('Permission denied. Please contact your Administrator for more permissions');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!$id) {
            $this->Session->setFlash("Invalid Link");
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
        $subject = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id)));
        //debug($categorydata);die();//$foldername=$categorydata['']
        if (!empty($subject)) {
            $dir = WWW_ROOT . 'img/uploads/Subjects/' . $subject['Subject']['image'];
            if ($this->Subject->delete($id)) {
                $file = new File($dir);
                $file->delete();
                $this->Session->setFlash("Subject deleted");
                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->params['named']['status']));
            }
        } else { /*         * ******* In case category not found.Redirect with error message ***** */
            $this->Session->setFlash('Subject Not found.');
            $this->redirect(array('controller' => 'Subject', 'action' => 'index', 'status' => $this->params['named']['status']));
        }
    }

    function admin_flagged() {
        $this->paginate = array('limit' => '10');

        $data = $this->paginate('FlaggedSubject');

        $this->set('subjects', $data);
    }

    function admin_delete_flagged($id=null) {
        if ($id) {
            if ($this->FlaggedSubject->delete($id)) {
                $this->Session->setFlash('Successfully deleted');
                $this->redirect(array('action' => 'admin_flagged'));
            }
        } else {
            $this->redirect(array('controller' => 'Subejcts', 'action' => 'admin_flagged'));
        }
    }

    function rate() {

        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', -1);
            $this->autoRender = false;
            $adjective_ids = array();
            $new_adj = array();
            if (isset($_POST['subject_id'])) {
                // print_r($this->Auth);
                $response = array('error' => false, 'login' => true, 'canRate' => true, 'subjectID' => '0');
                if ($this->Auth->User('id')) {
                    $this->data['SubjectRate']['subject_id'] = $_POST['subject_id'];
                    $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                    $this->data['SubjectRate']['rating'] = $_POST['rating'];
                    $check = $this->rate_time($this->data['SubjectRate']['subject_id'], $this->data['SubjectRate']['user_id']);
                    if ($check == '0') {
                        if (isset($_POST['adj1'])) {
                            if (!is_numeric($_POST['adj1'])) {
                                $new_adj[] = $_POST['adj1'];
                            } else {
                                $adjective_ids[] = $_POST['adj1'];
                            }
                        }
                        if (isset($_POST['adj2'])) {
                            if (!is_numeric($_POST['adj2'])) {
                                $new_adj[] = $_POST['adj2'];
                            } else {
                                $adjective_ids[] = $_POST['adj2'];
                            }
                        }
                        if ($_POST['adj3']) {
                            if (!is_numeric($_POST['adj3'])) {
                                $new_adj[] = $_POST['adj3'];
                            } else {
                                $adjective_ids[] = $_POST['adj3'];
                            }
                        }
                        //print_r($adjective_ids);
                        //print_r($new_adj);
//die();
//print_r($check);die();
                        if ($this->Subject->SubjectRate->save($this->data)) {
                            $data = mysql_query("SELECT MAX(balance) as balance FROM user_credits where user_id='" . $this->data['SubjectRate']['user_id'] . "'");
                            $row = mysql_fetch_array($data);
                            $sql = mysql_query("INSERT into user_credits (`subject_id`,`credit_id`,`user_id`,`credit`,`balance`,`created`)
                                         VALUES('" . $this->data['SubjectRate']['subject_id'] . "','1','" . $this->data['SubjectRate']['user_id'] . "','1','" . ($row['balance'] + 1) . "',NOW())");
                            if (count($new_adj) > 0) {
                                foreach ($new_adj as $adj):
                                    $query = mysql_query("INSERT INTO `suggested_adjectives` (`title`,`user_id`,`subject_id`,`created`,`modified`,`status`)
                            VALUES ('" . ucfirst($adj) . "','" . $this->data['SubjectRate']['user_id'] . "','" . $this->data['SubjectRate']['subject_id'] . "',NOW(),NOW(),'1')");
                                endforeach;
                            }
                            if (count($adjective_ids) > 0) {
                                foreach ($adjective_ids as $adj):
                                    $query = mysql_query("INSERT INTO `subject_adjectives` (`adjective_id`,`user_id`,`subject_id`,`created`,`status`)
                            VALUES ('" . $adj . "','" . $this->data['SubjectRate']['user_id'] . "','" . $this->data['SubjectRate']['subject_id'] . "',NOW(),'0')");
                                endforeach;
                            }
                            $this->Session->setFlash('Thanks for rating');
                            $response['error'] = false;
                            $response['subjectID'] = $this->data['SubjectRate']['subject_id'];
                            //echo $this->base.'/Subjects/subject/'.$this->data['SubjectRate']['subject_id'];
                        }
                    }else {
                        $response['error'] = true;
                        $response['canRate'] = false;
                        //echo "You Can't rate a Subject within seven days.";
                    }
                } else {
                    $response['error'] = true;
                    $response['login'] = false;

                    //              echo "Login First";
                }


                print_r(json_encode($response));
            }
        }
    }

    function admin_rate() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);

            $this->autoRender = false;
            if (isset($_POST['id'])) {
                $this->data['SubjectRate']['subject_id'] = $_POST['id'];
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];

                if ($this->Subject->SubjectRate->save($this->data)) {
                    $data = mysql_query("SELECT MAX(balance) as balance FROM user_credits where user_id='" . $_SESSION['Auth']['User']['id'] . "'");
                    $row = mysql_fetch_array($data);
                    $sql = mysql_query("INSERT into user_credits (`subject_id`,`credit_id`,`user_id`,`credit`,`balance`,`created`)
                                         VALUES('" . $_POST['id'] . "','1','" . $_SESSION['Auth']['User']['id'] . "','1','" . ($row['balance'] + 1) . "',NOW())");
                    $this->Session->setFlash('Thanks for rating');
                }
            }
        }
    }

    /*     * ****************************************************************   Custom Functions Starts           *********************************************************** */

    /*     * **************** This function will return the adjectives to add and edit VIEWS. To be called from autocomplete widget *********************** */

    function admin_adjectives() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $adjectives = $this->Adjective->find('all', array('conditions' => array('Adjective.title LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
            $i = 0;
            foreach ($adjectives as $adjective) {
                $response[$i]['id'] = $adjective['Adjective']['id'];
                $response[$i]['name'] = "" . $adjective['Adjective']['title'] . "";
                $i++;
            }
            if (isset($_GET["callback"])) {
                $response = $_GET["callback"] . "(" . $response . ")";
            }

            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************************** Adjective function ends  *********************************** */


    /*     * **************** This function will return the adjectives for front end withh option to suggest. To be called from autocomplete widget *********************** */

    function subject($id=null) {
        Configure::write('debug', 0);
        if ($id) {
            $subject = $this->Subject->find('first', array('conditions' => array('Subject.id' => $id,'Subject.status'=>'1')));
            if($subject){
            /*             * ********* Find Current Users rating for the subject********** */
//            foreach ($subject['SubjectRate'] as $rating) {
//                if($this->Auth->User('id')){
//                if ($rating['user_id'] == $_SESSION['Auth']['User']['id']) {
//                    $subject['Subject']['urated'] = $rating['rating'];
//                    break;
//                }
//                }
//            }

            /*             * **********find average rating of subject******** */

            $result = Set::classicExtract($subject, 'SubjectRate.{n}.rating');
            $subject['Subject']['avg_rating'] = array_sum($result) / count($result);

            /*             * ******Average Rating Ends ***** */

            /********************************/
        if(count($subject['SubjectAdjectives'])>0){
            $this->set('topadjectives',$this->top_adjectives($subject));
        }
            /********************************/
            
            $history=$this->Subject->SubjectRate->find('all',array('conditions'=>array('SubjectRate.subject_id'=>$id),'order'=>array('SubjectRate.created asc'),'fields'=>array('AVG(SubjectRate.rating) AS rating','SubjectRate.created'),'group'=>array('DATE(SubjectRate.created)')));
            $output='[';
            $output_array=array();
            $i=0;
            foreach ($history as $data):$i++;
                $output_array[$i]="['".$data['SubjectRate']['created']."',".round($data['0']['rating'],2)."]";
            endforeach;
            $output_data=implode(',',$output_array);
            $output='['.$output_data.']';
            $this->set('history',$output);
            $this->set('subject', $subject);
            $taglist = $this->get_taglist($subject['Subject']['tag_ids']);
            $this->set('tags', $taglist);
            $this->Subject->User->unbindModel(array('hasMany'=>array('UserCredit','Subject','SubjectRate')));
           $find_creator_info=$this->Subject->User->find('first',array('conditions'=>array('User.id'=>$subject['Subject']['user_id']),'fields'=>array('User.username','User.email','UserProfile.screenname','UserProfile.image')));
           $this->set('creator',$find_creator_info);

           /******************** Meter Content   ***********************/
           
           $randomSubjectIds = $this->Subject->find('list', array('conditions'=>array('Subject.image !='=>'','Subject.17+'=>'0','Subject.status'=>'1'),'fields' => 'id','order' => 'RAND()','limit' => 50));
           $subjects = $this->Subject->find('all', array('contain' => array('Subject.subject','Subject.desc','Subject.id','Subject.image'),
                                                         'conditions' => array('Subject.id' => $randomSubjectIds,'Subject.image <>'=>''),
                                                         'order' => 'RAND()'));
    
        $this->set('subjects',$subjects);           
        $this->Subject->User->unbindModel(array('hasMany'=>array('UserCredit','Subject','SubjectRate','Comment')));
        $comments=$this->Subject->Comment->find('all',array('conditions'=>array('Comment.subject_id'=>$subject['Subject']['id']),'fields'=>array('Comment.id','Comment.comment','Comment.created','Comment.user_id','User.id','User.username'),'recursive'=>'2'));
      
       
 $comments=$this->voted($comments);  $this->set('comments',$comments); 
 
            //debug($this->Auth);
            
}else{
    $this->Session->setFlash('Subject Not available');
    $this->redirect(array('controller'=>'Homes','action'=>'index'));
}  
        }
    }
/**************************Functions USed in Subject Function   **************************/    
    
    function top_adjectives($data){
        //debug($data['SubjectAdjectives']);
        $adjectives='';
        $adjective_ids=set::classicExtract($data['SubjectAdjectives'],'{n}.adjective_id');
        $count=array_count_values($adjective_ids);
        $total_adjectives=count($data['SubjectAdjectives']);
        
        $i='0';
        foreach($count as $key=>$value):
            $i++;
            $data=$this->Adjective->find('first',array('conditions'=>array('Adjective.id'=>$key),'fields'=>array('Adjective.title','Adjective.id')));
            $percentage=round(($value/$total_adjectives)*100,1);
            $adjectives[$i]['title']=$data['Adjective']['title'];
            $adjectives[$i]['percentage']=$percentage;
            
        endforeach;
        $result = Set::sort($adjectives, '{n}.percentage', 'desc');
        return $result;
    }
    
     function get_taglist($tag_ids=null) {
        $ids = explode(',', $tag_ids);
        $tags = array();
        foreach ($ids as $key => $id) {
            $taglist[$id] = $this->find_parenttags($id, $tags);
       }

        return $taglist;
    }

    function find_parenttags($id, $tags) {
        $data = $this->Tag->find('first', array('conditions' => array('Tag.id' => $id, 'Tag.type' => 'tag'), 'fields' => array('Tag.id', 'Tag.level', 'Tag.parent_id', 'Tag.title')));
        $tags[] = $data['Tag'];
        //debug($tags);
        if ($data['Tag']['level'] > 2) {
            return $this->find_parenttags($data['Tag']['parent_id'], $tags);
        }
        return $tags;
        
    }
    
    function voted($comments){
        $i=0;
        foreach($comments as $comment){
            
            if(!empty($comment['CommentVote'])){
                echo $_SESSION['Auth']['User']['id'];
                $user_ids=set::extract($comment['CommentVote'],'{n}.user_id');
                if(in_array($_SESSION['Auth']['User']['id'],$user_ids))$comments[$i]['voted']=1;else  $comments[$i]['voted']=0;
                 $comments[$i]['agree']=array_sum(set::extract($comment['CommentVote'],'{n}.agree'));
                $comments[$i]['disagree']=array_sum(set::extract($comment['CommentVote'],'{n}.disagree'));
                
                
            }else $comments[$i]['voted']=0;
            $i++;
        }
       
        return $comments;
    }

/********************  subject functions ENDS   ****************************/
    
    function comment(){
        if(isset($this->data)){
    //debug($this->data);die();
            $this->Subject->Comment->set($this->data);
            $insert_comment=mysql_query("INSERT INTO `comments` (`subject_id`,`user_id`,`comment`,`created`,`modified`) VALUES ('".$this->data['Comment']['subject_id']."','".$this->data['Comment']['user_id']."','".$this->data['Comment']['comment']."',NOW(),NOW())");
            if($insert_comment){
                //$this->Session->setFlash('');
                $this->redirect(array('controller'=>'Subjects','action'=>'subject',$this->data['Comment']['subject_id']));
            }
        }
    }
    
    function comment_vote(){
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            if(isset($_POST['type'] ) && isset($_POST['id'])){
                if($_POST['type']=='agree'){
                    $insert_vote=mysql_query("INSERT INTO `comment_votes` (`comment_id`,`user_id`,`agree`,`created`) VALUES('".$_POST['id']."','".$_SESSION['Auth']['User']['id']."','1',NOW())") or die(mysql_error());
                }else if($_POST['type']=='disagree'){
                    $insert_vote=mysql_query("INSERT INTO `comment_votes` (`comment_id`,`user_id`,`disagree`,`created`) VALUES('".$_POST['id']."','".$_SESSION['Auth']['User']['id']."','1',NOW()) ") or die(mysql_error());
                }
                if($insert_vote){
                    $count_votes=mysql_query("SELECT SUM(`agree`) as agree,SUM(`disagree`) as disagree from comment_votes where comment_id='".$_POST['id']."'") or die(mysql_error());
                    $count=mysql_fetch_assoc($count_votes);
                        $response['result']="true";
                        $response['agree']=$count['agree'];
                        $response['disagree']=$count['disagree'];
                        $response['cid']=$_POST['id'];
                        $response['html']="<li><img src='/ratetheu/img/front/up.gif' alt='agree'/>".$count['agree']."</li><li><img src='/ratetheu/img/front/dn.gif' alt='agree'/>".$count['disagree']."</li><li><a href='#' class='report' type='report' cid='".$_POST['id']."'><img src='/ratetheu/img/front/report-btn.png' alt=''/></a></li>";
                    }else{
                        $response['result']="false";
                    }
                $response=json_encode($response);     
               echo $response; 
            }
        } 
    }
    
    function report_comment(){
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
           if(isset($_POST['id']) && !empty($_POST['comment'])){
               $insert=mysql_query("INSERT INTO reported_comments (`comment_id`,`user_id`,`comment`,`created`) VALUES ('".$_POST['id']."','".$_SESSION['Auth']['User']['id']."','".$_POST['comment']."',NOW())");
               if($insert){
                   echo "<div class='register-form' style='line-height:50px;font-size:15px;text-align:center; font-weight:bold;'>Thanks For Reporting this Comment</div>";
               }
           }
        }
    
    }
    
    
    function adjectives() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $adjectives = $this->Adjective->find('all', array('conditions' => array('Adjective.title LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
            $i = 0;
            if ($adjectives) {
                foreach ($adjectives as $adjective) {
                    $response[$i]['id'] = $adjective['Adjective']['id'];
                    $response[$i]['name'] = "" . $adjective['Adjective']['title'] . "";
                    $i++;
                }
                if (isset($_GET["callback"])) {
                    $response = $_GET["callback"] . "(" . $response . ")";
                }
            } else {
                $response[$i]['id'] = $_GET['q'];
                $response[$i]['name'] = "" . $_GET['q'] . "";
            }
            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************************** Adjective function ends  *********************************** */

    
    
    function admin_synonyms() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 2);
            $this->autoRender = false;
            $response = array();
            $subjectlist = array();
            //echo $_POST['search'];
            //$data = mysql_query("SELECT `subject`,`desc` from `subject` where `subject` LIKE '%" . $_GET['search'] . "%' || `desc` LIKE '%" . $_GET['search'] . "%'") or die(mysql_error());
            $data = mysql_query("SELECT `subject`,`desc` from `subject` WHERE `subject`!='" . $_GET['search'] . "'") or die(mysql_error());
            while ($row = mysql_fetch_array($data)) {
                if (!empty($row['desc'])) {
                    $subjectlist[] = $row['subject'] . " (" . $row['desc'] . ")";
                    //$subjectlist[] = $row['subject'] . " " . $row['desc'];
                } else {
                    $subjectlist[] = $row['subject'];
                }
            }


            //$data=$this->Subject->find('all',array('conditions'=>array('Subject.subject LIKE'=>'%'.$_GET['search'].'%')));
            // print_r($subjectlist);
//$_GET['offset']=0;
            //echo "<pre>";
            //print_r($subjectlist);

            $i = 0;
            $offset = 0;
        $search=stripslashes ($_GET['search']);
            $response = array(array('id' => $search, 'name' => $search));
            $searchfor = str_replace(' ', '_', ucfirst($search));
            $result = $this->get_wiki_titles($response, $searchfor, $offset, $i, $subjectlist);
            //$result = $this->get_wiki_titles($response,$_GET['search'], $offset, $i,$subjectlist);
//            foreach ($result->query->search as $subject) {
//                if (!in_array($subject->title, $subjectlist)) {
//                    $response[$i]['id'] = $subject->title;
//                    $response[$i]['name'] = $subject->title;
//                    $i++;
//                } else if ($i == '51') {
//                    break;
//                } else {
//                    continue;
//                }
//            }

            $response = json_encode($result);
            echo $response;


//
//echo "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&limit=20&search=".$_POST['search'];
//            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
//            $i = 0;
//            foreach ($subjects as $subject) {
//                $response[$i]['id'] = $subject['Subject']['id'];
//                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "";
//                $i++;
//            }
//            if (isset($_GET["callback"])) {
//                $response = $_GET["callback"] . "(" . $response . ")";
//            }
//
//            $response = json_encode($response);
//            echo $response;
        }
    }

//    function admin_synonymsbackup() {
//        if ($this->RequestHandler->isAjax()) {
//            Configure::write('debug', 0);
//            $this->autoRender = false;
//            $response = array();
//            $subjectlist=array();
//            //echo $_POST['search'];
//       
////
////echo "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&limit=20&search=".$_POST['search'];
//
//            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
//            $i = 0;
//            foreach ($subjects as $subject) {
//                $response[$i]['id'] = $subject['Subject']['id'];
//                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "";
//                $i++;
//            }
//            if (isset($_GET["callback"])) {
//                $response = $_GET["callback"] . "(" . $response . ")";
//            }
//
//            $response = json_encode($response);
//            echo $response;
//        }
//    }
//    
//
    /*     * ************************** Tag function is called from edit and add. Called in Option tree  widget. ********************************************* */

    function admin_tags() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            if (!isset($_GET['id'])) {
                $_GET['id'] = '2';
            }
            $this->autoRender = false;
            if (isset($_GET['id']) && $_GET['id'] != '0') {
                $tags = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $_GET['id'], 'Tag.type !=' => 'attribute'), 'order' => 'Tag.position asc'));
            }
            if (!empty($tags)) {
                $response['0'] = "select Tag";
            }
            $i = 0;

            foreach ($tags as $tag) {
                $response[$tag['Tag']['id']] = "" . $tag['Tag']['title'] . "";
                $i++;
            }
            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************ Tag function ends************ */

    function get_parent_list($id, $result_arr=array()) {
        $tag = $this->Tag->find('first', array('conditions' => array('Tag.id =' => $id)));
        $result_arr[] = array('id' => $tag['Tag']['parent_id'], 'title' => $tag['Tag']['title']);

        if ($tag['Tag']['level'] > '2') {
            return $this->get_parent_list($tag['Tag']['parent_id'], $result_arr);
        }
        return $result_arr;
    }

    function formated_tags($title_arr, $saparater='>') {
        $titles = '';
        $title_arr = array_reverse($title_arr);
        foreach ($title_arr as $title) {

            $titles.=$saparater . $title['title'];
        }
        return substr($titles, strlen($saparater));
    }

    /*     * ******************* Function  to delete image while editing subject************************* */

    function admin_delete_image($id=null) {
        if (!empty($id)) {

            $query = mysql_query("UPDATE `subject` set `image`='' WHERE id='" . $id . "'");
            $data = $this->Subject->find('first', array('conditiond' => array('Subject.id =' => $id)));
            $dir = WWW_ROOT . 'img/uploads/Subjects/' . $data['Subject']['subject'] . '/' . $data['Subject']['image'];
            $file = new File($dir);
            if ($query) {
                if ($file) {
                    $file->delete();
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'edit', $id));
                }
            }
        }
    }

    

    function synonymlist($id) {
        if ($id) {
            $data = $this->Subject->find('all', array('conditions' => array('Subject.subject_id' => $id), 'fields' => array('Subject.subject', 'Subject.id')));
            //debug($data);
            $synonym_data = array();

            $i = 0;
            foreach ($data as $subject) {
                $synonym_data[$i]['id'] = $subject['Subject']['id'];
                $synonym_data[$i]['name'] = $subject['Subject']['subject'];
                $i++;
            }
            return $synonym_data;
        }
    }

    function admin_attributes($id=null) {
        $this->layout = 'Ajax';
        /*         * ******** Initialize all variables here********* */


        /*         * *************Initialization Ends*************** */

        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            //$this->autoRender = false;
            //$this->layout='Ajax';

            $id = $_REQUEST['id'];
            $old_attrib_num = $_POST['num'];      //Number of Attribute fields already in the form.
            if ($old_attrib_num == '0') {
                $n = 0;
            } else {
                $n = ceil($old_attrib_num / 3) + 1;
            }
            $metadata = array('n' => $n, 'id' => $id);
            $data = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $id, 'Tag.type =' => 'attribute')));
            $this->set('attributes', $data);
            $this->set('meta', $metadata);


            //$this->render('/elements/admin_attributes');
        }
    }

    function formated_attributes($attributes, $i) {

        $result = "<div class='inputattributes'><div style='float:left; padding-right:10px;'>" . $attributes['Tag']['title'] . "</div>
                <div >
                <input id='Attribute" . $i . "attribute' type='hidden' name='data[Attribute][$i][attribute]' value='" . $attributes['Tag']['title'] . "'/>
                " . $this->Form->input('Attribute' . $i . 'value') . "</div></div><br><div style='clear:both;height:10px;'></div>";
        return $result;
    }

    /*     * ********************  This Function will ruturn the search result for subjects    ********************* */

    function admin_search() {

        $data = $this->paginate('Subject', array('OR' => array(array('Subject.desc =' => $this->data['Subject']['search']), array('Subject.subject =' => $this->data['Subject']['search']))));
        $adjectives = '';
        $taglist = '';
        $i = 0;

        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */

        foreach ($data as $value) {
            $adj_ids = explode(',', $value['Subject']['adjective_ids']);
            $tag_ids = explode(',', $value['Subject']['tag_ids']);

            /*             * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
            foreach ($adj_ids as $id) {
                $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $id)));
                $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
            }


            /*             * ************** 
             * This loop will get all the formated tags for a particular record.
             *  Functions used : 
             *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
             *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
             * 
             * *************** */
            foreach ($tag_ids as $tid) {
                $tag_arr = $this->get_parent_list($tid);
                $taglist = $this->formated_tags($tag_arr, '>');
            }
            $data[$i]['Subject']['adjective_ids'] = substr($adjectives, 1);
            $data[$i]['Subject']['tag_ids'] = $taglist;
            $i++;
            $adjectives = '';
            //$tags='';
        }

        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('Subjects', $data);
    }

    /*     * ******************** This function  is used in autocomplete for search in subject   ******************* */

    function admin_search_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => $_GET['q'] . '%'),'fields'=>array('Subject.subject','Subject.id','Subject.desc')));
            if (empty($subjects)) {
                $subjects = $this->Subject->find('all', array('conditions' => array('Subject.desc LIKE' => $_GET['q'] . '%')));
            }
            $i = 0;
            
            foreach ($subjects as $subject) {
                $specifier='';
                $response[$i]['id'] = $subject['Subject']['subject'];
                if($subject['Subject']['desc']){
                    $specifier='('.$subject['Subject']['desc'].')';
                }
                $response[$i]['name'] = "" . $subject['Subject']['subject'] .$specifier;
                $i++;
            }
            if (isset($_GET["callback"])) {
                $response = $_GET["callback"] . "(" . $response . ")";
            }

            $response = json_encode($response);
            echo $response;
        }
    }

    function admin_subject_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $title = $_GET['title'];
            $specifier = $_GET['specifier'];
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject' => $title, 'Subject.desc' => $specifier)));

            if ($subjects) {
                return true;
            } else {
                return false;
            }
        }
    }

    function check_image_extension($ext) {
        $response = false;
        $allowedext = array('jpg', 'JPG', 'jpeg', 'JPEG', 'pjpeg', 'png', 'PNG');
        foreach ($allowedext as $extension) {
            if ($extension == $ext) {
                $response = true;
                break;
            }
        }
        return $response;
    }

    function admin_tag() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            $ids = array_reverse($this->get_parent_list($_POST['id']));
            // print_r($ids);
            foreach ($ids as $value) {
                $id = $id . $value['id'] . ',';
            }
            echo $id . $_POST['id'] . ',0';


            //echo '206,243,205,0';
            $response = json_encode($response);
            //echo $response;
        }
    }

    function admin_update() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            if (!empty($_POST['id'])) {
                //$query=mysql_query('UPDATE ');

                $this->Subject->id = $_POST['id'];
                $this->data['Subject']['status'] = $_POST['status'];
                $this->Subject->save($this->data);
            }
        }
    }

    function admin_report() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            if (!empty($_POST['id'])) {
                //$query=mysql_query('UPDATE ');
                $query = mysql_query("INSERT INTO `flagged_subjects` (`subject_id`,`user_id`,`type`,`comment`,`created`,`modified`)
                                                VALUES('" . $_POST['subject_id'] . "','" . $_POST['id'] . "','" . $_POST['type'] . "','" . $_POST['comment'] . "',now(),now())
                                   ");
                echo "<div class='thanks'>Thanks for reporting</div>";
            }
        }
    }

    function saveCredit($data) {
        $p = 0;

        $balance = $this->balance($data['User']['id']);

        foreach ($data['Subject'] as $key => $value) {
            if ($value == '1') {
                $point = $this->Credit->find('first', array('conditions' => array('Credit.id' => $key)));

                $this->data['UserCredit'][$p]['credit'] = $point['Credit']['point'];
                $this->data['UserCredit'][$p]['credit_id'] = $key;
                $this->data['UserCredit'][$p]['user_id'] = $data['User']['id'];
                $this->data['UserCredit'][$p]['subject_id'] = $data['Subject']['id'];

                $this->data['UserCredit'][$p]['balance'] = $balance + $this->data['UserCredit'][$p]['credit'];
                //$this->UserCredit->save($this->data['UserCredit']);
                $balance = $this->data['UserCredit'][$p]['balance'];
                $p++;
            }
        }
        if (!empty($this->data['UserCredit'])) {
            $this->UserCredit->saveAll($this->data['UserCredit']);
        }
    }

    function balance($id) {
        $points = $this->Subject->query("SELECT SUM(user_credits.credit) as balance FROM `user_credits` where user_id='$id'");
        return @$points[0][0]['balance'];
    }

    /*     * ***************  This function will set the current edited subject as a base subject for the selected  Subject synonyms. It takes $this->data as parameter********************** */

    function set_base_subject($data) {
        $subject_ids = explode(',', $this->data['Subject']['subject_ids']);
        $old_subject_ids = explode(',', $this->data['Subject']['old_subject_ids']);

        $deletedsyn = array_diff($old_subject_ids, $subject_ids);
        // debug($subject_ids);
        //debug($data);die();
        foreach ($deletedsyn as $id) {
            $update_subject_id = $this->Subject->query("UPDATE `subject` set `subject_id`='0' WHERE `id`='" . $id . "'");
        }
        foreach ($subject_ids as $subject_id)
            $update_subject_id = $this->Subject->query("UPDATE `subject` set `subject_id`='" . $this->data['Subject']['id'] . "' WHERE `id`='" . $subject_id . "'");
        return true;
    }

    function get_suggestion() {
        
        $subjects = $this->Page->find('all', array('limit' => '100', 'conditions' => array('Page.page_title LIKE' => $search . '%', 'Page.page_is_redirect' => '0'), 'fields' => array('Page.page_id', 'Page.page_title'), 'recursive' => '-1'));

//        foreach($subjects as $key1=>$redirects):
//            foreach($redirects['Pageredirect'] as $key=>$value):
//                $find_redirect=$this->Page->find('first',array('conditions'=>array('Page.page_id'=>$value['rd_from'])));
//                if($find_redirect){
//                    
//                
//                $subjects[$key1]['Page']['redirect_title'][$key]['id']=$find_redirect['Page']['page_id'];    
//                $subjects[$key1]['Page']['redirect_title'][$key]['title']=$find_redirect['Page']['page_title'];
//                }
//            endforeach;
//        endforeach;
//        //debug($results);  

        $this->set('subjects', $subjects);
    }

    function get_wiki_titles($response, $search, $offset, $i, $subjectlist) {
//      $res=json_encode($response);
//        print_r($subjectlist);
//        $useragent = env('HTTP_USER_AGENT');
//        $url = "http://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=intitle%3A".urlencode($_GET['search'])."%&srprop=hasrelated&srlimit=50&sroffset=" . $offset . "&format=json&what=title";
//        //echo $url;die();
//        $ch = curl_init($url);
//
//   set user agent
//       curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
///////  $ch = curl_init ($url) ;
//       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//       $res = json_decode(curl_exec($ch));
//       print_r($res);
//       curl_close($ch);
//       die();//print_r($res);
        //$search=htmlspecialchars_decode ($search);
        $subjects = $this->Page->find('all', array('limit' => '100', 'conditions' => array('Page.page_title LIKE' => $search . '%', 'Page.page_is_redirect' => '0','Page.page_namespace' => '0'), 'fields' => array('DISTINCT Page.page_title','Page.page_id'), 'recursive' => '-1'));
        if ($subjects) {
            foreach ($subjects as $subject) {
                if (!in_array($subject['Page']['page_title'], $subjectlist) && !in_array($subject['Page']['page_title'], $response)) {
                    if (!strpos($subject['Page']['page_title'], '(disambiguation)')) {
                        $response[$i]['id'] = $subject['Page']['page_title'];
                        $response[$i]['name'] = str_replace('_', ' ', $subject['Page']['page_title']);
                        $i++;
                    }
                }
                if ($i == '50') {
                    break;
                }
            }

            if ($i < '50' && count($subjects) > '50') {
                return $this->get_wiki_titles($response, $search, 50 + $offset, $i, $subjectlist);
            } else {
                if (count($response) > '0') {
                    return $response;
                }
            }
        }
        if (!$response) {

            //$findsubject=$this->Subject->find('all',array('limit'=>'1000','conditions'=>array('Subject.subject LIKE'=>$search)));
            //print_r($findsubject);
            //echo count($findsubject);

            $name = str_replace('_', ' ', $search);
            $response = array(array('id' => $name, 'name' => $name));
            return $response;
        }
        return $response;
    }

    function get_related_subjects($subject) {

        $data = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => $subject . ' %'), 'fields' => array('Subject.subject', 'Subject.desc')));
        foreach ($data as $key => $value) {
            $data[$key]['Subject']['rating_count'] = count($value['SubjectRate']);
        }
        return $data;
    }

    function get_redirects() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $result = '';
            $subjecttitle = $_POST['subject'];

            $data = $this->Pageredirect->find('all', array('conditions' => array('Pageredirect.rd_title' => $subjecttitle)));
            if ($data) {
                foreach ($data as $key => $titles):
                    foreach ($titles['Page'] as $redirects):

                        $result.=', ' . str_replace('_', ' ', $redirects['page_title']);
                    endforeach;
                endforeach;
            }
            $response = trim($result, ', ');
            //$response='adasdas';
            return $response;
            //debug($data);
            //$this->set('subjects', $result);
        }
    }

   
    
    

    function login_element() {
        //echo phpinfo();

        $this->layout = "";
        //echo $this->element('login');
    }

    /*     * *****************This function checks when was subject last rated by a user ********************************* */

    function rate_time($subject_id, $user_id) {
        $data = $this->Subject->SubjectRate->find('count', array(
            'conditions' => array(
                'SubjectRate.subject_id' => $subject_id,
                'SubjectRate.user_id' => $user_id,
                'SubjectRate.created >=DATE_SUB(CURDATE(),INTERVAL 7 DAY)'
            ),
            'order' => 'SubjectRate.created desc',
            'limit' => '1'
                )
        );

        return $data;
    }

    /*     * *********** This function will generate resized image for the rated subject **************** */

    function generatepopupimage() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->layout = "";
            $result = '';
            $subjectimage = $_POST['image'];
            $this->set('subjectsimage', $subjectimage);
        }
    }

    function admin_correction() {
//        $data=$this->Subject->find('all',array('recursive'=>'-1'));
//        debug($data);
//        foreach($data as $subject):
//            if(!empty($subject['Subject']['adjective_ids'])){
//                $adjective_ids=explode(',',$subject['Subject']['adjective_ids']);
//                foreach($adjective_ids as $adjective){
//                    $query=mysql_query("INSERT INTO  `subject_adjectives` (`adjective_id`,`user_id`,`subject_id`,`created`,`status`)
//                             VALUES ('".$adjective."','".$subject['Subject']['user_id']."','".$subject['Subject']['id']."','".$subject['Subject']['approved_on']."','0')");
//                }
//            }
//        endforeach;
//        
    }

    function multidimensional_search($parents, $searched) {
  if (empty($searched) || empty($parents)) {
    return false;
  }
 
  foreach ($parents as $key => $value) {
    $exists = true;
    foreach ($searched as $skey => $svalue) {
      $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
    }
    if($exists){ return $key; }
  }
 
  return false;
} 
}
?>